<?php

namespace App\Http\Controllers\Api;

use App\Events\NewUserEvent;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class LoginController extends BaseController
{
    const TOKEN_APP = 'app';
    /**
     * 密码登录
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request) {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'password' => 'required',
        ], [
            'required' => ':attribute 必填',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (empty($user)) {
            return response()->json([
                'msg' => "用户不存在",
                'code' => 500,
                'data' => null,
            ]);
        }
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'code' => 1,
                'msg' => '帐号或密码不正确'
            ]);
        } else if ($user->status != 1) {
            return response()->json([
                'msg' => "当前用户状态不能登录",
                'code' => 500,
            ]);
        } else {
            if (config('app.env') !== 'local') {
                $user->tokens()->where('name', self::TOKEN_APP)->delete();
            }

            return response()->json([
                'msg' => "ok",
                'code' => 0,
                'data' => [
                    'token' =>  $user->createToken(self::TOKEN_APP)->plainTextToken,
                    'uid' => $user->id,
                    'name' => $user->name,
                    'mobile' => $user->mobile,
                ],
            ]);
        }
    }

    /**
     * 使用验证码登录
     * @return JsonResponse
     */
    public function loginBySmsCode(Request $request) {

        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'sms_code' => 'required',
        ], [
            'required' => ':attribute 必填',
        ]);

        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (empty($user)) {
            return response()->json([
                'msg' => "用户不存在",
                'code' => 500,
                'data' => null,
            ]);
        }

        $key = sprintf("sms_%s", $request->mobile);
        if (Cache::get($key) != $request->sms_code) {
            return response()->json([
                'msg' => "验证码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }

        if ($user->status != 1) {
            return response()->json([
                'msg' => "当前用户状态不能登录",
                'code' => 500,
            ]);
        }

        // 登录成功
        if (config('app.env') !== 'local') {
            $user->tokens()->where('name', self::TOKEN_APP)->delete();
        }

        return response()->json([
            'msg' => "ok",
            'code' => 0,
            'data' => [
                'token' =>  $user->createToken(self::TOKEN_APP)->plainTextToken,
                'uid' => $user->id,
                'name' => $user->name,
                'mobile' => $user->mobile,
            ],
        ]);
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function sendSmsCode(Request $request) {
        if (empty($request->mobile)) {
            return response()->json([
                'msg' => "手机号码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }


        $key = sprintf("sms_%s", $request->mobile);
        $lock_key = sprintf("sms_%s_lock", $request->mobile);

        if (Cache::has($lock_key)) {
            return response()->json([
                'msg' => "请不要频繁操作",
                'code' => 500,
                'data' => null,
            ]);
        }
        $sms_code = random_int(100000, 999999);



        send_sms_login($request->mobile, $sms_code);
//        self::send_sms_login($request->mobile, $sms_code);

          Log::debug(sprintf("Login sms code %s : %s", $request->mobile, $sms_code));
            Cache::put($key, $sms_code, 1800);
            Cache::put($lock_key, true, 59);
            return response()->json([
                'msg' => '短信发送成功',
                'code' => 0,
                'data' => "短信发送成功",
            ]);

//        if (send_sms_login($request->mobile, $sms_code)) {
//            Log::debug(sprintf("Login sms code %s : %s", $request->mobile, $sms_code));
//            Cache::put($key, $sms_code, 1800);
//            Cache::put($lock_key, true, 59);
//            return response()->json([
//                'msg' => '短信发送成功',
//                'code' => 0,
//                'data' => "短信发送成功",
//            ]);
//        } else {
//            return response()->json([
//                'msg' => '短信发送失败',
//                'code' => 500,
//                'data' => "短信发送失败",
//            ]);
//        }
    }


//    public function send_sms_login($mobile,$sms_code)
//    {
//        print(send_sms_login($mobile, $sms_code));
//    }

    /**
     * 注册
     * @param Request $request
     * @return JsonResponse
     */
    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'name' => 'required',
            'password' => 'required',
            'sms_code' => 'required',
            'invite_code' => 'required',
        ], [
            'required' => ':attribute 必填',
        ]);
        if(!User::where('invite_code', $request->invite_code)->exists()){
            return response()->json([
                'msg' => "邀请码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }
        if ($validator->stopOnFirstFailure()->fails()) {
            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first(),
                'data' => null
            ]);
        }

        $key = sprintf("sms_%s", $request->mobile);
        if (Cache::get($key) != $request->sms_code) {
            return response()->json([
                'msg' => "验证码不正确",
                'code' => 500,
                'data' => null,
            ]);
        }
        $user = User::where('name', $request->name)->first();
        if (!empty($user)) {
            return response()->json([
                'msg' => "用户名已经被注册",
                'code' => 500,
                'data' => null,
            ]);
        }

        $user = User::where('mobile', $request->mobile)->first();
        if (!empty($user)) {
            return response()->json([
                'msg' => "手机号已经被注册",
                'code' => 500,
                'data' => null,
            ]);
        }

        $model = new User();
        $model->name = (string)$request->name;
        $model->mobile = (string) $request->mobile;
        $model->org_root = 200;
        $model->org_code = null;
        $model->gender = (int) $request->gender;
        $model->status = 1;
        $model->role = '';
        $model->kyc = 0;
        $model->money = 0;
        $model->ticket = 0;
        $model->password = Hash::make($request->password);
        $model->invite_code = Str::random(8);

        // 记录邀新用户
        if (!empty($request->invite_code)) {
            $referUser = User::where('invite_code', $request->invite_code)->first();
            if (!empty($referUser)) {
                $model->parent_id  = $referUser->id;
            }
        }

        if ($model->save()) {
            NewUserEvent::dispatch($model);

            return response()->json([
                'code' => 0,
                'msg' => '注册成功',
                'data' => [
                    'token' =>  $model->createToken(self::TOKEN_APP)->plainTextToken,
                    'uid' => $model->id,
                    'name' => $model->name,
                    'mobile' => $model->mobile,
                ],
            ]);
        } else {
            return response()->json([
                'code' => 1,
                'msg' => '注册失败',
                'data' => null
            ]);
        }
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function logout(Request $request) {
        $request->user()->tokens()->where('name', self::TOKEN_APP)->delete();

        return response()->json([
            'code' => 0,
            'msg' => 'ok'
        ]);
    }
}
